// 全局变量
let currentUser = null;
const BASE_URL = (typeof window !== 'undefined' && window.location && window.location.origin && window.location.origin.startsWith('http'))
	? window.location.origin
	: 'http://localhost:8080';

// DOM 加载完成后执行
 document.addEventListener('DOMContentLoaded', function() {
    // 初始化事件监听器
    initEventListeners();
    
    // 检查用户登录状态
    checkLoginStatus();
});

// 初始化事件监听器
function initEventListeners() {
    // 搜索相关
    document.getElementById('search-btn').addEventListener('click', performSearch);
    document.getElementById('search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') performSearch();
    });
    
    // 登录注册模态框
    document.getElementById('login-btn').addEventListener('click', function() {
        window.location.href = '/login.html';
    });
    document.getElementById('register-btn').addEventListener('click', function() {
        window.location.href = '/login.html';
    });
    
    // 关闭模态框
    document.querySelectorAll('.close-btn').forEach(btn => {
        btn.addEventListener('click', closeModal);
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(e) {
        if (e.target.className === 'modal') closeModal();
    });
    
    // 表单提交
    document.getElementById('login-form').addEventListener('submit', function(e) {
        e.preventDefault();
        submitLogin();
    });
    
    document.getElementById('register-form').addEventListener('submit', function(e) {
        e.preventDefault();
        submitRegister();
    });
    
    // 登出
    document.getElementById('logout-btn').addEventListener('click', logout);
    
    // 支付相关代码已移除
    
    // 用户中心点击事件
    document.getElementById('username-display').addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        window.location.href = 'user_center.html';
    });
    
    // AI助手悬浮球
    initAIAssistant();
}

// 检查用户登录状态
function checkLoginStatus() {
    // 从localStorage获取用户信息
    const userJson = localStorage.getItem('currentUser');
    if (userJson) {
        currentUser = JSON.parse(userJson);
        updateUIForLoggedInUser();
    }
}

// 执行搜索
function performSearch() {
    const query = document.getElementById('search-input').value.trim();
    if (!query) {
        alert('请输入搜索关键词');
        return;
    }
    try { addToHistory(query); } catch(e) {}
    
    // 显示加载状态
    const resultsContainer = document.getElementById('search-results');
    resultsContainer.innerHTML = '<div class="loading">搜索中..</div>';
    const t0 = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
    
    // 调用搜索API
    fetch(`${BASE_URL}/api/search?query=${encodeURIComponent(query)}`)
        .then(response => response.json())
        .then(data => {
            const t1 = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
            displaySearchResults(data, query);
            if (document.getElementById('search-meta')) {
                const ms = Math.max(1, Math.round(t1 - t0));
                document.getElementById('search-meta').textContent = `找到 ${data.length} 条结果，用时 ${ms} ms`;
            }
        })
        .catch(error => {
            resultsContainer.innerHTML = '<div class="error">搜索失败，请稍后重试</div>';
            console.error('搜索错误:', error);
        });
}

// 显示搜索结果
function displaySearchResults(data, query) {
    const resultsContainer = document.getElementById('search-results');
    
    if (!data || data.length === 0) {
        resultsContainer.innerHTML = '<div class="no-results">未找到相关结果</div>';
        return;
    }
    
    let html = `<h3>搜索结果 (关于: ${escapeHTML(query)})</h3>`;
    html += '<div class="results-list">';
    
    data.forEach(result => {
        const highlighted = highlightSnippet(result.snippet, query);
        html += `
        <div class="result-item">
            <h4 class="result-title"><a href="${escapeAttr(result.url)}" target="_blank">${escapeHTML(result.title)}</a></h4>
            <div class="result-url">${escapeHTML(result.url)}</div>
            <p class="result-snippet">${highlighted}</p>
        </div>
        `;
    });
    
    html += '</div>';
    resultsContainer.innerHTML = html;
}

function escapeHTML(s) {
    return String(s || '').replace(/[&<>\"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c] || c));
}

function escapeAttr(s) {
    return String(s || '').replace(/["'<>&]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[c] || c));
}

function highlightSnippet(snippet, query) {
    if (!snippet || !query) return escapeHTML(snippet || '');
    const terms = query.split(/\s+/).filter(Boolean).map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
    if (terms.length === 0) return escapeHTML(snippet);
    const re = new RegExp(`(${terms.join('|')})`, 'gi');
    return escapeHTML(snippet).replace(re, '<mark>$1</mark>');
}

// 打开登录模态框
function openLoginModal() {
    document.getElementById('login-modal').style.display = 'flex';
}

// 打开注册模态框
function openRegisterModal() {
    document.getElementById('register-modal').style.display = 'flex';
}

// 关闭模态框
function closeModal() {
    document.getElementById('login-modal').style.display = 'none';
    document.getElementById('register-modal').style.display = 'none';
}

// 提交登录
function submitLogin() {
    const username = document.getElementById('login-username').value;
    const password = document.getElementById('login-password').value;
    
    fetch(`${BASE_URL}/api/user/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 保存用户信息
            currentUser = { username, user_id: data.user_id };
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            
            // 更新UI
            updateUIForLoggedInUser();
            closeModal();
            alert('登录成功');
        } else {
            alert('登录失败: ' + (data.error || '用户名或密码错误'));
        }
    })
    .catch(error => {
        alert('登录失败，请稍后重试');
        console.error('登录错误:', error);
    });
}

// 提交注册
function submitRegister() {
    const username = document.getElementById('register-username').value;
    const password = document.getElementById('register-password').value;
    const phone = document.getElementById('register-phone').value;
    const email = document.getElementById('register-email').value;
    
    fetch(`${BASE_URL}/api/user/register`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password, phone, email })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 保存用户信息（如果后端返回user_id）
            if (data.user_id) {
                currentUser = { username, user_id: data.user_id };
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                updateUIForLoggedInUser();
            }
            alert('注册成功，请登录');
            closeModal();
            openLoginModal();
        } else {
            alert('注册失败：' + (data.error || '未知错误'));
        }
    })
    .catch(error => {
        alert('注册失败，请稍后重试');
        console.error('注册错误:', error);
    });
}

// 登出
function logout() {
    currentUser = null;
    localStorage.removeItem('currentUser');
    updateUIForLoggedOutUser();
    alert('已退出登录');
}

// 更新登录状态UI
function updateUIForLoggedInUser() {
    const loginBtn = document.getElementById('login-btn');
    const registerBtn = document.getElementById('register-btn');
    const userInfo = document.getElementById('user-info');
    const usernameDisplay = document.getElementById('username-display');
    const paymentPanel = document.getElementById('payment-panel');
    
    if (loginBtn) loginBtn.style.display = 'none';
    if (registerBtn) registerBtn.style.display = 'none';
    if (userInfo) userInfo.style.display = 'flex';
    if (usernameDisplay) usernameDisplay.textContent = currentUser.username;
    
    // 支付面板已移除
}

// 更新未登录状态UI
function updateUIForLoggedOutUser() {
    const loginBtn = document.getElementById('login-btn');
    const registerBtn = document.getElementById('register-btn');
    const userInfo = document.getElementById('user-info');
    const paymentPanel = document.getElementById('payment-panel');
    
    if (loginBtn) loginBtn.style.display = 'block';
    if (registerBtn) registerBtn.style.display = 'block';
    if (userInfo) userInfo.style.display = 'none';
    
    // 支付面板已移除
}

// 支付相关函数已移除

// 工具函数：获取用户信息
function getUserInfo(userId) {
    return fetch(`${BASE_URL}/api/user/info/${userId}`)
        .then(response => response.json());
}

// 支付相关工具函数已移除

// AI助手功能
function initAIAssistant() {
    const aiBall = document.querySelector('.ai-ball');
    const aiChatPanel = document.querySelector('.ai-chat-panel');
    const aiCloseBtn = document.querySelector('.ai-close-btn');
    const aiSendBtn = document.getElementById('ai-send-btn');
    const aiChatInput = document.getElementById('ai-chat-input');
    const aiChatMessages = document.getElementById('ai-chat-messages');
    
    // 点击AI球打开/关闭聊天面板
    aiBall.addEventListener('click', function(e) {
        e.stopPropagation();
        aiChatPanel.classList.toggle('active');
        if (aiChatPanel.classList.contains('active')) {
            aiChatInput.focus();
        }
    });
    
    // 关闭聊天面板
    aiCloseBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        aiChatPanel.classList.remove('active');
    });
    
    // 发送消息
    function sendAIMessage() {
        const message = aiChatInput.value.trim();
        if (!message) return;
        
        // 添加用户消息
        addAIMessage(message, 'user');
        aiChatInput.value = '';
        
        // 显示AI正在思考
        const thinkingMessage = addAIMessage('正在思考中...', 'assistant', true);
        
        // 调用AI API
        fetch(`${BASE_URL}/api/ai/query`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ query: message })
        })
        .then(response => response.json())
        .then(data => {
            // 移除思考消息
            thinkingMessage.remove();
            // 添加AI回复
            addAIMessage(data.answer || '抱歉，我暂时无法回答这个问题', 'assistant');
        })
        .catch(error => {
            // 移除思考消息
            thinkingMessage.remove();
            // 添加错误消息
            addAIMessage('抱歉，网络连接出现问题，请稍后重试', 'assistant');
            console.error('AI查询错误:', error);
        });
    }
    
    // 发送按钮点击事件
    aiSendBtn.addEventListener('click', sendAIMessage);
    
    // 输入框回车事件
    aiChatInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendAIMessage();
        }
    });
    
    // 点击页面其他地方关闭聊天面板
    document.addEventListener('click', function(e) {
        if (!aiChatPanel.contains(e.target) && !aiBall.contains(e.target)) {
            aiChatPanel.classList.remove('active');
        }
    });
}

// 添加AI消息到聊天面板
function addAIMessage(message, sender, isTemporary = false) {
    const aiChatMessages = document.getElementById('ai-chat-messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `ai-message ${sender}`;
    if (isTemporary) {
        messageDiv.classList.add('temporary');
    }
    messageDiv.textContent = message;
    
    // 移除欢迎消息（如果是第一条消息）
    const welcomeMessage = aiChatMessages.querySelector('.ai-welcome');
    if (welcomeMessage && aiChatMessages.children.length === 1) {
        welcomeMessage.remove();
    }
    
    aiChatMessages.appendChild(messageDiv);
    aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
    
    return messageDiv;
}

// 美化页面加载动画
document.addEventListener('DOMContentLoaded', function() {
    // 添加页面加载动画
    const body = document.body;
    body.style.opacity = '0';
    body.style.transition = 'opacity 0.5s ease-in-out';
    
    setTimeout(() => {
        body.style.opacity = '1';
    }, 100);
    
    // 为搜索框添加焦点效果
    const searchInput = document.getElementById('search-input');
    searchInput.addEventListener('focus', function() {
        this.parentElement.style.transform = 'scale(1.02)';
        this.parentElement.style.boxShadow = '0 15px 50px rgba(102, 126, 234, 0.3)';
    });
    
    searchInput.addEventListener('blur', function() {
        this.parentElement.style.transform = 'scale(1)';
        this.parentElement.style.boxShadow = '0 10px 40px rgba(0, 0, 0, 0.1)';
    });
    
    // 添加按钮悬停音效（可选）
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        button.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
        });
        
        button.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });
    try {
        const key = 'searchHistory';
        const arr = JSON.parse(localStorage.getItem(key) || '[]');
        const container = document.getElementById('quick-tags');
        if (container) {
            container.innerHTML = arr.map(q => `<span class="quick-tag" data-q="${q}">${q}</span>`).join('');
            container.querySelectorAll('.quick-tag').forEach(el => {
                el.addEventListener('click', () => {
                    document.getElementById('search-input').value = el.getAttribute('data-q');
                    performSearch();
                });
            });
        }
        const si = document.getElementById('search-input');
        if (si) {
            si.addEventListener('input', function() {
                const box = document.getElementById('suggestions');
                if (!box) return;
                const val = this.value.trim();
                if (val.length < 2) { box.classList.remove('active'); box.innerHTML=''; return; }
                const prompt = `请基于“${val}”给出5个相关搜索建议，要求只返回以换行分隔的短语，不要解释。`;
                fetch(`${BASE_URL}/api/ai/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: prompt }) })
                .then(r => r.json()).then(data => {
                    const ans = data.answer || '';
                    const lines = ans.split(/\r?\n/).map(s => s.trim()).filter(Boolean).slice(0,5);
                    if (lines.length === 0) { box.classList.remove('active'); box.innerHTML=''; return; }
                    box.innerHTML = lines.map(s => `<div class="suggestions-item" data-q="${s}">${s}</div>`).join('');
                    box.classList.add('active');
                    box.querySelectorAll('.suggestions-item').forEach(el => {
                        el.addEventListener('click', () => {
                            document.getElementById('search-input').value = el.getAttribute('data-q');
                            box.classList.remove('active');
                            box.innerHTML='';
                            performSearch();
                        });
                    });
                }).catch(() => { box.classList.remove('active'); box.innerHTML=''; });
            });
        }
    } catch(e) {}
});

// 监听来自登录页面的消息
window.addEventListener('message', function(event) {
    // 确保消息来源可信
    if (event.origin !== window.location.origin) {
        return;
    }
    
    const data = event.data;
    
    if (data.type === 'loginSuccess') {
        // 更新用户信息
        currentUser = data.user;
        localStorage.setItem('currentUser', JSON.stringify(currentUser));
        localStorage.setItem('sessionId', data.sessionId);
        
        // 更新UI
        updateUIForLoggedInUser();
        
        // 根据用户选择跳转到相应页面
        if (data.redirect === 'user_center') {
            window.location.href = 'user_center.html';
        } else {
            // 默认留在首页，可以显示登录成功提示
            const successMessage = document.createElement('div');
            successMessage.className = 'login-success-message';
            successMessage.textContent = '登录成功！欢迎回来，' + currentUser.username;
            successMessage.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #28a745;
                color: white;
                padding: 15px 20px;
                border-radius: 5px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 10000;
                animation: slideIn 0.3s ease-out;
            `;
            
            document.body.appendChild(successMessage);
            
            // 3秒后自动移除提示
            setTimeout(() => {
                successMessage.style.animation = 'slideOut 0.3s ease-out';
                setTimeout(() => {
                    if (successMessage.parentNode) {
                        successMessage.parentNode.removeChild(successMessage);
                    }
                }, 300);
            }, 3000);
        }
    }
    
    if (data.type === 'loginClosed') {
        // 登录窗口关闭的处理（如果需要的话）
        console.log('登录窗口已关闭');
    }
});

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);
